package com.example.rabbitmq.demo2_pub_confirm;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @Author songyahui
 * @Date 2023/7/12 18:21
 * @Description
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //注入发布确认回调接口
        rabbitTemplate.setConfirmCallback(this);
//        注入失败回退回调接口
        rabbitTemplate.setReturnsCallback(this);
    }
    /**
     * 交换机确认回调方法
     * 1.发送消息 交换机收到消息 回调
     *  correlationData 保存回调消息的ID和相关信息
     *  交换机收到消息 ack = true
     *  cause null
     * 2.发送消息 交换机接受失败 回调
     *  correlationData 保存回调消息的ID和相关信息
     *  交换机收到消息 ack = false
     *  cause 失败原因
     */
    @SneakyThrows
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData!=null ? correlationData.getId() : "";
        if(ack){
            log.info("确认回调：id:{}", id);
        }else {
            //不管是逮住消息内容或者消息标识，都有抓手去重复发起消息消费
            String message = correlationData!=null ? new String(correlationData.getReturned().getMessage().getBody(), "UTF-8") : null;
            log.info("交换机未接受到消息，id:{}，原因：{}, message: {}", id, cause, message);
        }
    }

    //将不可达的消息传递给生产者
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("消息：{};\r\n退回消息交换机：{};\r\n退回原因：{};\r\nrouting key：{}",new String(returnedMessage.getMessage().getBody()), returnedMessage.getExchange(), returnedMessage.getReplyText(), returnedMessage.getRoutingKey());
    }
}
